<template>
    <div
        class="page_root"
        :key="queryUpdateFlag"
        data-page-name="平台项目文件管理"
        data-page-identification="c_icf7osyvzl"
    >
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_plvqs5zfye 自定义模板_07gu9otazh -->
            <div class="flie-div">
                <div class="top-btn">
                    <div class="tip-msg">文件列表</div>
                    <a-space>
                        <a-button type="primary" v-permission="'50001252_vid_fmra50haqg'" @click="handleJump"
                            >文件上传</a-button
                        >
                        <a-button type="primary" @click="handleAdd" v-permission="'50001252_vid_gjd0ipzl60'"
                            >新建</a-button
                        >
                    </a-space>
                </div>
                <div class="table-box">
                    <!-- 表格 -->
                    <!-- 表格 -->
                    <a-table
                        :data-source="state.tableData"
                        :columns="state.columns"
                        :row-key="record => record.id"
                        bordered
                        :loading="state.tableLoading"
                        :pagination="false"
                    >
                        <template #bodyCell="{ column, record }">
                            <!-- 文件名称 -->
                            <template v-if="column.dataIndex === 'fileName'">
                                <a-input
                                    v-if="record.editing"
                                    v-model:value="record.fileName"
                                    placeholder="请输入文件名称"
                                />
                                <span v-else>{{ record.fileName }}</span>
                            </template>

                            <!-- Confluence链接 -->
                            <template v-else-if="column.dataIndex === 'link'">
                                <a-input
                                    v-if="record.editing"
                                    v-model:value="record.link"
                                    placeholder="请输入Confluence链接"
                                />
                                <a v-else :href="record.link" target="_blank">{{ record.link }}</a>
                            </template>

                            <!-- 备注 -->
                            <template v-else-if="column.dataIndex === 'description'">
                                <a-input
                                    v-if="record.editing"
                                    v-model:value="record.description"
                                    placeholder="请输入备注"
                                />
                                <span v-else>{{ record.description }}</span>
                            </template>

                            <!-- 操作 -->
                            <template v-else-if="column.dataIndex === 'operation'">
                                <a-space>
                                    <a-button
                                        v-if="record.editing"
                                        type="link"
                                        :disabled="record.okBtnLoading"
                                        size="small"
                                        @click="handleSave(record)"
                                    >
                                        完成
                                    </a-button>
                                    <a-button
                                        v-if="record.editing"
                                        type="link"
                                        size="small"
                                        @click="handleCancel(record)"
                                    >
                                        取消
                                    </a-button>
                                    <a-button
                                        v-if="!record.editing"
                                        type="link"
                                        size="small"
                                        @click="handleEdit(record)"
                                        v-permission="'50001252_vid_jxppkvw2hs'"
                                    >
                                        编辑
                                    </a-button>
                                    <a-popconfirm title="确认删除该行吗？" @confirm="handleDelete(record.id)">
                                        <a-button
                                            v-if="!record.editing"
                                            type="link"
                                            size="small"
                                            v-permission="'50001252_vid_3qxvrebw5k'"
                                        >
                                            删除
                                        </a-button>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- end vid_plvqs5zfye 自定义模板_07gu9otazh -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'useProjectId': {
            type: [String, Number],
            default: undefined
        },
        activeKey: String,
        refreshCount: Number
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    function checkRequired(value, msg = '必填项缺失') {
        if (value === undefined || value === null || value === '') {
            message.warning(msg) // 这里用 Antd 的 message，也可以改成 console.error 或 throw Error
            return false
        }
        return true
    }
    const state = reactive({
        tableData: [],
        tableLoading: false,
        uid: 0, // 自增 id
        columns: [
            {
                title: '序号',
                dataIndex: 'index',
                customRender: ({ index }) => index + 1,
                width: 60,
                align: 'center'
            },
            { title: '文件名称', dataIndex: 'fileName', align: 'center' },
            { title: 'Confluence链接', dataIndex: 'link', align: 'center' },
            { title: '备注', dataIndex: 'description', align: 'center' },
            {
                title: '操作',
                align: 'center',
                dataIndex: 'operation',
                width: 150
            }
        ]
    })
    watch(
        () => [props.useProjectId, props.activeKey, props.refreshCount],
        val => {
            getData()
        },
        { immediate: true }
    )
    function getData() {
        if (!checkRequired(props.useProjectId, '请选择产品')) return
        state.tableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/file_manage/product/search', {
            projectId: props.useProjectId
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    state.tableData = []
                    return
                }
                state.tableData = data.data
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    // 新增
    const handleAdd = () => {
        if (!checkRequired(props.useProjectId, '请选择产品')) return
        state.tableData.push({
            fileName: '',
            link: '',
            description: '',
            editing: true,
          isNew:true
        })
    }

    const editData = ref({})
    // 保存
    const handleSave = record => {
        if (!record.fileName || !record.link) {
            message.error('文件名称和Confluence链接为必填！')
            return
        }
        const missingFields = []

        if (!record.fileName) missingFields.push('文件名称')
        if (!record.link) missingFields.push('Confluence链接')
        if (missingFields.length > 0) {
            message.error(`请输入${missingFields.join('、')} ！`)
            return
        }
        editData.value = cloneDeep(record)
        record.okBtnLoading = true
        const api = editData.value.isNew ? post : put
        api('/solution-ppm/api/v2/built-in-system-ppm/file_manage/product', {
            ...editData.value,
            projectId: props.useProjectId
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)

                if (editData.value.isNew) {
                    // 新建数据的情况
                    const index = state.tableData.findIndex(item => item === record)
                    if (index !== -1) {
                        // 用后端返回的数据替换临时数据
                        state.tableData.splice(index, 1, {
                            ...data.data,
                            editing: false
                        })
                    }
                } else {
                    // 编辑现有数据的情况
                    Object.assign(record, data.data, { editing: false })
                }
                record.editing = false
            })
            .finally(() => {
                editData.value = {}
                record.okBtnLoading = false
            })
    }

    // 编辑
    const handleEdit = record => {
        record.editing = true
    }

    // 取消（如果是新建行就删除）
    const handleCancel = record => {
        if (!record.id) {
            state.tableData = state.tableData.filter(item => item.id !== record.id)
        } else {
            record.editing = false
        }
    }

    // 删除
    const handleDelete = id => {
        del(`/solution-ppm/api/v2/built-in-system-ppm/file_manage/product/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData()
        })
    }

    // 文件上传
    const handleJump = () => {
        get('/solution-ppm/api/v2/built-in-system-ppm/file_manage/confluence_url').then(data => {
            window.open(data.data, '_black')
        })
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/
    .top-btn {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
        align-items: center;
    }
    .tip-msg {
        padding-left: 8px;
        border-left: 4px solid #3875ff;
        height: 16px;
        font-size: 16px;
        font-weight: 600;
        line-height: 16px;
    }
    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
    /*样式*/
</style>
